package rs.networx.servlets;

import java.io.IOException;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import rs.networx.dao.PersonDao;
import rs.networx.entity.Person;

public class DeleteFriendLoggedUserServlet extends HttpServlet {

	private static final long serialVersionUID = -2556104910943723104L;

	@EJB
	private PersonDao personDao;

	private String username;
	private String password;
	private Integer intLoggedUserID;
	private Person loggedUser;

	private String personToDeleteID;
	private Integer intPersonToDeleteID;
	private Person personToDelete;

	private boolean pass;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {

		System.out.println("LOADED: DeleteFriendLoggedUserServlet");

		response.setContentType("text/html; charset=UTF-8");
		request.setCharacterEncoding(response.getCharacterEncoding());

		HttpSession session = request.getSession();
		loggedUser = (Person) session.getAttribute("logovaniUser");

		personToDeleteID = request.getParameter("personID");

		try {
			username = loggedUser.getEmail();
			password = loggedUser.getPassword();
			intLoggedUserID = loggedUser.getId();
			System.out.println(username + "  " + password + "  "
					+ intLoggedUserID);

			intPersonToDeleteID = Integer.parseInt(personToDeleteID);
			System.out.println(personToDeleteID + "  " + intPersonToDeleteID);
		} catch (Exception e) {

		}

		// nadjemo osobu za brisanje...
		personToDelete = personDao.findById(intPersonToDeleteID);
		System.out.println("personToDelete: " + personToDelete);

		if (loggedUser != null) {
			if (personToDelete != null) {
				pass = personDao.removeFromFriends(intLoggedUserID,
						intPersonToDeleteID);
				if (pass) {

					response.sendRedirect("ViewPersonsFriendsLoggedUserServlet");
					return;
				} else if (!pass) {
					// ako je doslo do greske prilikom brisanja, opet
					// redirektujemo...
					response.sendRedirect("ViewPersonsFriendsLoggedUserServlet");
					return;
				}
			} else if (personToDelete == null) {
				// ako nema osobe za brisanje, opet redirektujemo...
				response.sendRedirect("ViewPersonsFriendsLoggedUserServlet");
				return;
			}
		} else if (loggedUser != null) {
			// ako nema ulogovanog korisnika, redirektujemo na pocetnu
			// stranicu...
			request.getRequestDispatcher("Welcome.jsp").forward(request,
					response);
			return;
		}
	}

	// --------------------------------------------------------------------------------------------------------------------------------------------------
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		doGet(request, response);
	}

}
